﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace FDSQLAssistant.Extensions
{
    public static class ObjExtension
    {
        public static string ToJson(this object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        public static T FomJson<T>(this string str)
        {
            return JsonConvert.DeserializeObject<T>(str);
        }

        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str) || str.Trim().Length == 0;
        }

        public static void Output(this object obj, string msg, bool bReturn = true)
        {
            if (bReturn)
                Console.WriteLine(msg);
            else
                Console.Write(msg);
        }

        public static string ReadLine(this object obj)
        {
            return Console.ReadLine();
        }

        public static bool ContainsIgnoreCase(this string str, string subString)
        {
            if (str.IsNullOrEmpty())
                return false;
            return str.IndexOf(subString, StringComparison.OrdinalIgnoreCase) != -1;
        }

        public static bool ContainsIgnoreCaseAny(this string str, params string[] subStrs)
        {
            if (str.IsNullOrEmpty() || subStrs == null || subStrs.Length == 0)
                return false;
            foreach (var sub in subStrs)
            {
                if (str.ContainsIgnoreCase(sub))
                {
                    return true;
                }
            }

            return false;
        }

        public static bool ContainsIgnoreCase(this string[] strs, string subStr)
        {
            if (strs == null || strs.Length == 0 || subStr.IsNullOrEmpty())
                return false;
            return strs.Contains(subStr, new StringEqualityComparer());
        }

        public static bool ContainsIgnoreCase(this string[] strs, params string[] subStrs)
        {
            if (strs == null || strs.Length == 0 || subStrs == null || subStrs.Length == 0)
                return false;
            foreach (var sub in subStrs)
            {
                if (strs.Contains(sub, new StringEqualityComparer()))
                {
                    return true;
                }
            }

            return false;
        }
        
        private class StringEqualityComparer : IEqualityComparer<string>
        {
            public bool Equals(string x, string y)
            {
                return x.Equals(y, StringComparison.OrdinalIgnoreCase);
            }

            public int GetHashCode(string obj)
            {
                return obj.GetHashCode() + GetHashCode();
            }
        }
    }
}
